// app.js
var util = {};
var BaiduAppId = 'apppikmjgngjhig';
// util.baseurl = 'https://gz.gzrzvisa.com/';
util.baseurl = 'http://127.0.0.1:31842/';
util.baseurl = 'https://test.gzrzvisa.com/';
util.url = {
  'getToken': util.baseurl + 'data/api.login/register',
  'getMember': util.baseurl + 'data/api.auth.center/get',
};
// import Aegis from '../static/aegis'
import {genTestUserSig} from './debug/GenerateTestUserSig'
App({
  onLaunch() {
    
    var that = this;
    const isSupport = !!wx.getMenuButtonBoundingClientRect
    const rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null
    wx.getSystemInfo({
      success: res => {
        that.globalData.navigationBarHeight = res.statusBarHeight + (rect.top - res.statusBarHeight) * 2 + rect.height;
      }
    });
    const { model, system, statusBarHeight } = wx.getSystemInfoSync()
    let headHeight
    if (/iphone\s{0,}x/i.test(model)) {
      headHeight = 88
    } else if (system.indexOf('Android') !== -1) {
      headHeight = 68
    } else {
      headHeight = 64
    }

    this.globalData.headerHeight = headHeight
    this.globalData.statusBarHeight = statusBarHeight
  },
  aegisReportEvent(name, ext1) {
    if(!this.aegisReportEvent[name]) {
      wx.aegis.reportEvent({
        name,
        ext1,
        ext2: 'wxSimpleDemo',
        ext3: genTestUserSig('').sdkAppID,
      })
      this.aegisReportEvent[name] = true
    }
  },
  globalData: {
    navigationBarHeight: 0,
    baseurl: util.baseurl,
    // 第一张价格
    main_price: 100,
    // 第二张价格
    assistant_price: 20,
    getToken: util.baseurl + 'data/api.login/register',
    getMember: util.baseurl + 'data/api.auth.center/get',

    headerHeight: 0,
    statusBarHeight: 0,
  },

  //获取登录token
  getTokens() {
    var token = wx.getStorageSync('token');
    var phone = wx.getStorageSync('phone');
    if (token == '') {
      const obj = wx.getLaunchOptionsSync()
      return new Promise(function (resolve, reject) {
        wx.login({
          success: loginres => {
            wx.request({
              url: util.url.getToken,
              data: {
                code: loginres.code,
                phone: phone,
                path: obj.path,
                scene: obj.scene,
                where: 1,
              },
              header: {
                'api-token': token,
                'api-name': 'wap'
              },
              success: function (res) {
                if (res.data.errno != 0) {
                  //   wx.showModal({
                  //     title: '提示',
                  //     content: res.data.msg,
                  //   })
                } else {
                  wx.setStorageSync('token', res.data.token.token);
                  //   wx.setStorageSync('phone', res.data.phone);
                  resolve(res.data.token);
                }
              },
            })
          }
        })
      });
    } else {
      return new Promise(function (resolve, reject) {
        resolve(token);
        //console.log(token)
      });
    }
  },
  //获取登录用户详细信息
  async getMember() {
    let token = await this.getTokens();
    return new Promise(function (resolve, reject) {
      wx.request({
        url: util.url.getMember,

        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'api-token': token,
          'api-name': 'wap'
        },
        success: function (userInfo) {
          resolve(userInfo.data.data);
        }
      });
    });
  },

  /** 
检查session是否过期,更新sessionkey(获取手机号和UNIID时使用)
*/
  checksession() {
    return new Promise(function (resolve, reject) {
      wx.checkSession({
        success: function () {
          console.log('没过期')
          console.log(wx.getStorageSync('token'))
          resolve(wx.getStorageSync('token'));
        },
        fail: function () {
          console.log('已过期')
          console.log(util.url.getToken)
          wx.login({
            success: loginres => {
              wx.request({
                url: util.url.getToken,
                data: {
                  code: loginres.code
                },
                success: function (res) {
                  if (res.data.errno != 0) {
                    wx.showModal({
                      title: '提示',
                      content: res.data.msg,
                    })
                    return
                  } else {
                    wx.setStorageSync('token', res.data.token);
                    resolve(res.data.token);

                  }
                },
              })
            }
          })
        }
      })
    });
  },

  /**
   * get请求
   */
  _get(url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();
    let _this = this;
    // 构造请求参数
    data = data || {};
    //console.log(util.baseurl);
    // 构造get请求
    let request = () => {
      var token = wx.getStorageSync('token');
      wx.request({
        url: util.baseurl + url,
        header: {
          'content-type': 'application/json',
          'token': token
        },
        data: data,
        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            console.log(res);
            _this.showError('网络请求出错');
            return false;
          }
          if (res.data.code === -1) {
            // 登录态失效, 重新登录
            wx.hideNavigationBarLoading();
            _this.doLogin(2);
          } else if (res.data.code === 0) {
            _this.showError(res.data.msg, () => {
              fail && fail(res);
            });
            return false;
          } else {
            success && success(res.data);
          }
        },
        fail(res) {
          _this.showError(res.errMsg, () => {
            fail && fail(res);
          });
        },
        complete(res) {
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? _this.doLogin(request) : request();
  },
  /**
   * post提交
   */
  _post_form(url, data, success, fail, complete, isShowNavBarLoading) {
    let _this = this;
    isShowNavBarLoading || true;
    var token = wx.getStorageSync('token');
    // 在当前页面显示导航条加载动画
    if (isShowNavBarLoading == true) {
      wx.showNavigationBarLoading();
    }
    wx.request({
      url: util.baseurl + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': token,
        'api-token': token,
        'api-name': 'wechat'
      },
      method: 'POST',
      data: data,
      success(res) {
        // if (res.statusCode !== 200 || typeof res.data !== 'object') {
        //   _this.showError('网络请求出错');
        //   return false;
        // }
        console.log(res.data.code);

        if (res.data.code === -1 || res.data.code == 401 || res.code == 401) {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          _this.doLogin(1);
          return false;
        } else if (res.data.code === 0) {
          _this.showError(res.data.msg, () => {
            fail && fail(res);
          });
          let is_notary = wx.getStorageSync('is_notary');
                console.log('is_notary'+is_notary);
                if(typeof is_notary != 'undefined' && is_notary>0){
                        //要延时执行的代码
                        // _this.setData({
                            // login_tips: '身份验证成功，登陆中...',
                        // })
                        wx.showToast({
                            title: '身份验证成功，登陆中...',
                            icon: 'success',
                            mask: true,
                            duration: 1500
                        });
                        setTimeout(function () {
                            wx.reLaunch({
                                url: '/pages/mine/index',
                            })
                        }, 800) //延迟时间
                    // wx.reLaunch({
                    //     url: '/pages/mine/index',
                    // })
                }else{
                    // _this.showError(res.errMsg, () => {
                    //     fail && fail(res.data.info);
                    // });
                }
          return false;
        }
        success && success(res.data);
      },
      fail(res) {
        console.log(res);
        _this.showError(res.errMsg, () => {
          fail && fail(res);
        });
      },
      complete(res) {
        wx.hideNavigationBarLoading();
        // wx.hideLoading();
        complete && complete(res);
      }
    });
  },
  /**
   * 显示成功提示框
   */
  showSuccess(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'none',
      mask: true,
      duration: 1500,
      success() {
        callback && (setTimeout(() => {
          callback();
        }, 1500));
      }
    });
  },
  /**
   * 显示失败提示框
   */
  showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(() => {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },
  /**
   * 验证登录
   */
  checkIsLogin() {
    //验证登录
    return wx.getStorageSync('token') != '';
    // return wx.getStorageSync('phone') != '';
  },
  doLogin() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = '/' + currentPage.route //当前页面url
    let to_url = '/pages/login/index'
    if (url !== to_url) {
      wx.navigateTo({
        url: to_url,
      })
    }
  }
})